package tower

import "fmt"

// AirTrafficControl 中介者接口
type AirTrafficControl interface {
	Notify(sender Aircraft, event EventType, msg string)
}

// ControllerTower 具体中介者 - 飞机塔台
type ControllerTower struct {
	aircrafts []Aircraft
}

// Register 注册飞机
func (ct *ControllerTower) Register(aircraft Aircraft) {
	ct.aircrafts = append(ct.aircrafts, aircraft)
}

// Notify 通知其他飞机
func (ct *ControllerTower) Notify(sender Aircraft, event EventType, msg string) {

	fmt.Printf("\n塔台收到来自 [%s] 的消息: %s %s\n", sender.GetName(), event, msg)

	switch event {
	case EventTypeLand:
		// TODO
		ct.handleLandingRequest(sender)
	case EventTypeTakeoff:
		ct.handleTakeoffRequest(sender)
	case EventTypeLocation:
		ct.broadcastPosition(sender, string(event))
	}
}

// handleLandingRequest 处理降落请求
func (ct *ControllerTower) handleLandingRequest(aircraft Aircraft) {
	fmt.Printf("塔台处理 [%s] 的降落请求\n", aircraft.GetName())
	// 检查跑道状态
	runwayFree := true
	for _, a := range ct.aircrafts {
		if a.IsOnRunway() {
			runwayFree = false
			break
		}
	}

	if runwayFree {
		ct.sendMessage(aircraft, "跑道空闲，允许降落")
		aircraft.SetOnRunway(true)
	} else {
		ct.sendMessage(aircraft, "跑道已被占用，请等待")
	}
}

// handleTakeoffRequest 处理起飞请求
func (ct *ControllerTower) handleTakeoffRequest(aircraft Aircraft) {
	fmt.Printf("塔台处理 [%s] 的起飞请求\n", aircraft.GetName())

	if !aircraft.IsOnRunway() {
		ct.sendMessage(aircraft, "允许起飞")
		aircraft.SetOnRunway(false)
	} else {
		ct.sendMessage(aircraft, "请先进入跑道")
	}
}

// sendMessage 发送消息给飞机
func (ct *ControllerTower) sendMessage(aircraft Aircraft, message string) {
	for _, ac := range ct.aircrafts {
		if ac != aircraft {
			ac.Receive(fmt.Sprintf("[塔台指令] %s", message))
			return
		}
	}
}

// broadcastPosition 广播飞机位置
func (ct *ControllerTower) broadcastPosition(aircraft Aircraft, msg string) {
	for _, ac := range ct.aircrafts {
		if ac != aircraft {
			ac.Receive(fmt.Sprintf("[位置更新] %s %s", ac.GetName(), msg))
		}
	}
}
